<script lang="ts" setup>
import { onActivated, onMounted, onUnmounted, ref, watch } from 'vue';

import { v4 as uuidv4 } from 'uuid';

import { reqSetPositionSymbol, reqSupportedSymbolByName } from '#/api/system';
import useWebSocket from '#/hooks/useWebSocket';

import { followColumn } from '../indexcolumn';

const props = defineProps(['platform']);

const wsUUID = uuidv4();

const symbolList = ref([]);

const { ws, connect, messages, sendMessage, closeConnection } = useWebSocket(
  import.meta.env.VITE_GLOB_WS_URL as string,
);

interface ISymbol {
  id: number;
  symbol: string;
  open_show?: number;
}

const supportSymbol = ref<ISymbol[]>([]);

const getSupportSymbol = async () => {
  const result = await reqSupportedSymbolByName(props.platform.name);
  supportSymbol.value = result;
  symbolList.value = result.filter((item: any) => item.open_show);
};

const init = () => {
  getSupportSymbol();

  if (ws.value) {
    closeConnection();
  }
  connect(() => {
    sendMessage(
      JSON.stringify({
        id: wsUUID,
        op: 'web.account',
        value: props.platform.name,
      }),
    );
  });
};
watch(
  () => props.platform,
  () => {
    init();
    getSupportSymbol();
  },
  { deep: true },
);

const setPositionType = async (symbols: ISymbol[]) => {
  const params = {
    platform_id: props.platform.id,
    symbols: symbols.map((item) => item.symbol),
  };

  await reqSetPositionSymbol(params);
};

const handleOptionChange = (v: ISymbol[]) => {
  setPositionType(v);
};

onActivated(() => {
  init();
});

onMounted(() => {
  init();
});

onUnmounted(() => {
  closeConnection();
});
</script>

<template>
  <div class="page-content">
    <div class="flex items-center justify-between p-3">
      <span>持仓数据</span>
      <el-select
        v-model="symbolList"
        multiple
        collapse-tags
        style="width: 220px"
        value-key="id"
        @change="handleOptionChange"
      >
        <el-option
          v-for="item in supportSymbol"
          :key="item.id"
          :label="item.symbol"
          :value="item"
        />
      </el-select>
    </div>
    <ReTable :columns="followColumn" :data="messages" :height="550" />
  </div>
</template>

<style lang="scss" scoped>
.page-content {
  padding: 10px 20px 20px;
  margin-top: 20px;
  background-color: hsl(var(--background));
  border-radius: 4px;
}
</style>
